package com.example.zhangch.myapplication;


        import android.app.ProgressDialog;
        import android.content.ContentResolver;
        import android.content.DialogInterface;
        import android.content.Intent;
        import android.graphics.Bitmap;
        import android.graphics.BitmapFactory;
        import android.net.Uri;
        import android.os.Bundle;
        import android.support.v7.app.AppCompatActivity;
        import android.text.TextUtils;
        import android.util.Log;
        import android.view.View;
        import android.widget.ImageView;
        import android.widget.TextView;
        import android.widget.Toast;
        import com.loopj.android.http.BinaryHttpResponseHandler;
        import com.loopj.android.http.SyncHttpClient;
        import com.loopj.android.http.TextHttpResponseHandler;
        import com.qiniu.android.http.ResponseInfo;
        import com.qiniu.android.storage.UpCancellationSignal;
        import com.qiniu.android.storage.UpCompletionHandler;
        import com.qiniu.android.storage.UpProgressHandler;
        import com.qiniu.android.storage.UploadManager;
        import com.qiniu.android.storage.UploadOptions;
        import org.json.JSONException;
        import org.json.JSONObject;

        import java.io.ByteArrayOutputStream;
        import java.io.FileNotFoundException;
        import java.io.IOException;
        import java.io.InputStream;
        import java.text.SimpleDateFormat;
        import java.util.Date;

        import cz.msebera.android.httpclient.Header;

public class activity_upload extends AppCompatActivity {

    private TextView title;  //显示上传结果
    private ImageView image;  //显示下载的图片内容
    private ProgressDialog progressDialog;  //上传进度提示框
    private boolean isProgressCancel;  //网络请求过程中是否取消上传或下载
    private UploadManager uploadManager;  //七牛SDK的上传管理者
    private UploadOptions uploadOptions;  //七牛SDK的上传选项
    private UpProgressHandler upProgressHandler;  //七牛SDK的上传进度监听
    private UpCancellationSignal upCancellationSignal;  //七牛SDK的上传过程取消监听
    private final static String TOKEN_URL = "http://xxx.xxx.xxx/x/";  //服务器请求token的网址
    private String uptoken;  //服务器请求Token值
    private String upKey;  //上传文件的Key值
    private byte[] upLoadData;  //上传的文件

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        initView();
       // initData();
        uptoken="UBubqd_IuffEWcUytSmz2bBTuXy9OdSW-kyPz8lQ:99KnKIEpHosujZMiCKafMaPF3Ek=:eyJzY29wZSI6IiBkb25naW1hZ2UiLCJkZWFkbGluZSI6MTUwMDQzOTc3Nn0=";
        uploadManager = new UploadManager();
        upProgressHandler = new UpProgressHandler() {
            /**
             * @param key 上传时的upKey；
             * @param percent 上传进度；
             */
            @Override
            public void progress(String key, double percent) {
                progressDialog.setProgress((int) (upLoadData.length * percent));
            }
        };
        upCancellationSignal = new UpCancellationSignal() {
            @Override
            public boolean isCancelled() {
                return isProgressCancel;
            }
        };
        //定义数据或文件上传时的可选项
        uploadOptions = new UploadOptions(
                null,  //扩展参数，以<code>x:</code>开头的用户自定义参数
                "mime_type",  //指定上传文件的MimeType
                true,  //是否启用上传内容crc32校验
                upProgressHandler,  //上传内容进度处理
                upCancellationSignal  //取消上传信号
        );
    }


    private String getPicture() {
        //模拟上传图片的byte数组，并返回文件名

        return "upload.txt";
    }
    private void initView() {
        title = (TextView) findViewById(R.id.title);
        image = (ImageView) findViewById(R.id.image);
    }



    /**
     * 点击按钮，开始文件上传
     *
     * @param view
     */
    public void clickPost(View view) {
        uptoken="UBubqd_IuffEWcUytSmz2bBTuXy9OdSW-kyPz8lQ:1Fp6kyqtbzrTYpP92PNDAiZmZG0=:eyJzY29wZSI6ImRvbmdpbWFnZSIsImRlYWRsaW5lIjoxNTAwNDQ2OTc5fQ==";
        UploadManager uploadManager = new UploadManager();
        // 设置图片名字
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String key = "icon_" + sdf.format(new Date());
        uploadManager.put(upLoadData, key, uptoken, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject res) {
                // info.error中包含了错误信息，可打印调试
                // 上传成功后将key值上传到自己的服务器
            }
        }, null);
    }
    public void chosepic(View view) {
        Intent intent = new Intent();
                /* 开启Pictures画面Type设定为image */
        intent.setType("image/*");
                /* 使用Intent.ACTION_GET_CONTENT这个Action */
        intent.setAction(Intent.ACTION_GET_CONTENT);
                /* 取得相片后返回本画面 */
        startActivityForResult(intent, 1);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            Uri uri = data.getData();
            Log.e("uri", uri.toString());
            ContentResolver cr = this.getContentResolver();
            try {
                //存储图片,变成byte形式，便于在上面取出
                byte[] buffer=new byte[1024];
                InputStream in=   cr.openInputStream(uri);
                //下面是将图片读成字节，而且是以1024为单位读的
                ByteArrayOutputStream baos=new ByteArrayOutputStream();
               //定义整数类型对象
                int number;
                try{
                    while((number=in.read(buffer, 0, buffer.length))>0)
                    {
                        baos.write(buffer, 0, number);
                    }
                }catch(IOException e ){
//即使你能保证读取能成功，你也要做好读取错误后的处理，否则通不过编译
                    System.out.println("读取失败！");
                }
                //利用循环方式将图片读完整

                //将字节保存到byte[]数组对象中
                upLoadData=baos.toByteArray();
                Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));

                /* 将Bitmap设定到ImageView */
                image.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                Log.e("Exception", e.getMessage(),e);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


}
